package com.duanjw.mybatis.spring.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @author duanjw
 */
@Configuration
@ComponentScan("com.duanjw.mybatis.spring")
//@MyScann
//@MapperScan
@MapperScan("com.duanjw.mybatis.spring.mapper")
public class AppConfig {
    /**
     * mybatis配置
     *
     * @param dataSource
     * @return
     */
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * dataSource
     *
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        //加载驱动
        driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        //数据库路径
        String url = "jdbc:mysql://rm-bp1qmk7v384kq7y2gpo.mysql.rds.aliyuncs.com:3306/test";
        driverManagerDataSource.setUrl(url);
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("Duan1234");
        return driverManagerDataSource;
    }

    @Bean
    public SqlSessionTemplate sqlSession(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
